
import { _decorator, BaseNode, Component, EditBox, game, instantiate, Label, Node, PolygonCollider2D, Sprite, SpriteFrame, tween, Tween, v2, v3, Vec3 } from 'cc';
import { PropupBase } from '../propup/PropupBase';
import { GlobalVar } from '../GlobalVar';
import { mapNameConfig, ModelGame } from './ModelGame';
import { GameEvent, WssEvent } from '../EventName';

const { ccclass, property } = _decorator;
export const rewardConfig = {
    ticket: { icon: 0 },
    GOLD: { icon: 1 },
    COPPER_ORE: { icon: 2, nodeName: "tong" },
    GOLD_ORE: { icon: 3, nodeName: "jin" },
    DIAMOND_ORE: { icon: 4, nodeName: "zuan" },
}
@ccclass('GamePanel')
export class GamePanel extends PropupBase {
    @property(Node)
    renwuItem: Node = null;
    @property(Node)
    boosItem: Node = null;
    @property(Node)
    uis: Node = null;
    @property(Node)
    personItem: Node = null;
    @property(Node)
    dituNode: Node = null;
    @property(EditBox)
    coinEditBox: EditBox = null;
    @property(Label)
    totalLabel: Label = null;
    @property(Label)
    timeLabel: Label = null;

    isSchedule: boolean = false;
    createTime: number = 0;
    allDiTu: Array<any> = [];
    protected onLoad(): void {
        super.onLoad()
        this.allDiTu = this.node.getChildByName("allditu").children;
        game.on(WssEvent.ON_ADVENTURE_LAND_DATA, this.ON_ADVENTURE_LAND_DATA, this);
        game.on(WssEvent.ON_ADVENTURE_BOOS, this.initBoos, this);
        game.on(GameEvent.OPEN_ORE, this.openOre, this);
    }
    start(): void {

    }
    onAddCoinBtnClick() {
        let coin = Number(this.coinEditBox.string);
        let nowCoin = Number(GlobalVar.userInfo.walletList[0].normalBalance);
        if (coin + 10000 > nowCoin) {
            return;
        }
        let addCoin = coin + 10000;
        if (addCoin <= 0) {
            addCoin = 0;
        }
        ModelGame.getInstance().addInputCoin = addCoin;
        this.coinEditBox.string = addCoin.toString();
    }

    onMinusCoinBtnClick() {
        let coin = Number(this.coinEditBox.string);

        let addCoin = coin - 10000;
        if (addCoin <= 10000) {
            addCoin = 10000;
        }
        ModelGame.getInstance().addInputCoin = addCoin;
        this.coinEditBox.string = addCoin.toString();
    }
    editChange() {
        console.log(Number(this.coinEditBox.string))
        if (Number(this.coinEditBox.string) < 10000) {
            this.coinEditBox.string = "10000"
        }
        ModelGame.getInstance().addInputCoin = Number(this.coinEditBox.string)
    }
    onConfirmBtnClick() {
        if (ModelGame.getInstance().addInputCoin > Number(GlobalVar.userInfo.walletList[0].normalBalance)) {
            console.log("金币不够")
            game.emit(GameEvent.SHOW_TOAST, "Not enough coin")
            return;
        }
        let data = {
            cmd: 7,
            body: {
                amount: ModelGame.getInstance().addInputCoin,
            }
        }
        GlobalVar.wssAD.sendBinaryMessage(data)
        game.emit(GameEvent.SHOW_TOAST, "Bid  " + ModelGame.getInstance().addInputCoin + "  success")
    }
    public initPanel() {
        let data = {
            cmd: 6,
            body: {
                amount: ModelGame.getInstance().nowInputCoin,
                area: mapNameConfig[GlobalVar.areaIndex],
            }
        }
        GlobalVar.wssAD.sendBinaryMessage(data)
        this.removeAllPerson();
        ModelGame.getInstance().addInputCoin = 10000;
        this.coinEditBox.string = String(ModelGame.getInstance().addInputCoin)
        //this.totalLabel.string = String(GlobalVar.userInfo.walletList[0].normalBalance);
    }
    private removeAllPerson() {
        let child = this.dituNode.children;
        for (let i = 0; i < child.length; i++) {
            child[i].removeAllChildren()
        }
    }
    initBoos(data?: any) {
        let node = this.dituNode.getChildByName(data.body.area)
        let boos = instantiate(this.boosItem);
        node.addChild(boos);
        boos.active = true;
        boos.setPosition(0, 0, 0);
        this.scaleForever(boos);
    }
    openOre(data?: any) {
        let arr = data.body;
        for (let i = 0; i < arr.length; i++) {
            let node = this.uis.getChildByName(arr[i].area);
            let nodeName = rewardConfig[arr[i].coin.name].nodeName;
            let oreNode = node.getChildByName(nodeName)
            if (oreNode && oreNode.active == false) {
                oreNode.active = true;
                this.scaleForever(oreNode, 1.2, 0.9);
            }
        }
    }
    scaleForever(node, scale1: number = 1.1, scale2: number = 1) {
        Tween.stopAllByTarget(node)
        tween()
            .target(node)
            .to(0.5, { scale: v3(1.1, 1.1, 1.1) })
            .to(0.5, { scale: v3(1, 1, 1) })
            .union()
            .repeatForever()
            .start()
    }
    updateTime() {
        let nowTime = Date.now();
        let timestr = Math.floor(60 - (nowTime - this.createTime) / 1000)
        if (timestr < 0) {
            timestr = 0;
        }
        this.timeLabel.string = String(timestr);
        if (timestr <= 0) {
            this.unschedule(this.updateTime);
            this.isSchedule = false;
        }
    }
    ON_ADVENTURE_LAND_DATA(data?: any) {
        console.log(data, "冒险之地数据")
        let ditudata = data.body.areas;
        // this.createTime = data.body.timestamp;
        if (!this.isSchedule) {
            this.isSchedule = true;
            this.createTime = data.body.timestamp;
            this.updateTime();
            this.schedule(this.updateTime, 1);
        }
        for (let key in ditudata) {
            let node = this.dituNode.getChildByName(key);
            let uinode = this.uis.getChildByName(key);
            let nowdata = ditudata[key];
            this.updateDiTuPerson(node, nowdata.headcount);
            this.updateUILabel(uinode, nowdata.coin)
            this.closeIcon(uinode);
        }

        this.totalLabel.string = String(data.body.coin.value);
    }
    private updateDiTuPerson(node: Node, num: number) {
        if (num > node.children.length) {
            let needNum = num - node.children.length;
            for (let i = 0; i < needNum; i++) {
                let pos = v2(0, 0);
                let points = node.getComponent(PolygonCollider2D).points;
                pos.set(ModelGame.getInstance().getRandomPointInPolygon(points));
                pos.y += 144;
                let person = instantiate(this.personItem);
                node.addChild(person);
                person.active = true;
                let pos1 = v3(pos.x, pos.y + 200, 0);
                let pos2 = v3(pos.x, pos.y, 0);
                person.setPosition(pos1);
                if (node.name == mapNameConfig[GlobalVar.areaIndex] && !node.getChildByName(GlobalVar.userInfo.username)) {
                    person.name = GlobalVar.userInfo.username;
                    this.personMoveTo(person, pos2, true);
                } else {
                    this.personMoveTo(person, pos2);
                }
            }
            this.personSort(node);
        }
    }
    private personSort(node: Node) {
        // 获取所有子节点
        let children = node.children;
        // 将子节点按 y 坐标排序，从大到小
        children.sort((a, b) => b.position.y - a.position.y);
    }
    private personMoveTo(node: Node, pos: Vec3, isself = false) {
        Tween.stopAllByTarget(node)
        let jiangluo = node.getChildByName("jiangluo");
        let zhanli = node.getChildByName("zhanli");
        let nameLabel = node.getChildByName("name");
        jiangluo.active = true;
        zhanli.active = false;
        nameLabel.active = false;
        node.angle = 0;
        tween()
            .target(node)
            .parallel(
                tween().to(6, { position: pos })
                    .call(() => {
                        jiangluo.active = false;
                        zhanli.active = true;
                        nameLabel.active = true;
                        let str = this.generateRandomString();
                        let num = Math.floor(Math.random() * 5) + 1;
                        for (let i = 0; i < num; i++) {
                            str += '*';
                        }
                        if (isself) {
                            nameLabel.getComponent(Label).string = GlobalVar.userInfo.username;
                        } else {
                            nameLabel.getComponent(Label).string = str;
                        }
                    }),
                tween().to(0.5, { angle: 10 }).to(1, { angle: -10 }).to(0.5, { angle: 0 })
                    .union().repeat(3)
            )
            .start()
        // tween()
        //     .target(node)
        //     .to(1, { position: pos })
        //     .call(() => {
        //         jiangluo.active = false;
        //         zhanli.active = true;
        //         nameLabel.active = true;
        //         let str = this.generateRandomString();
        //         let num = Math.floor(Math.random() * 5) + 1;
        //         for (let i = 0; i < num; i++) {
        //             str += '*';
        //         }
        //         nameLabel.getComponent(Label).string = str;
        //     })
        //     .start()
    }
    private getRandomUpperCaseLetter(): string {
        const charCode = Math.floor(Math.random() * 26) + 65; // 65 是 'A' 的 ASCII 码
        return String.fromCharCode(charCode);
    }
    private generateRandomString(length: number = 2): string {
        let result = '';
        for (let i = 0; i < length; i++) {
            result += this.getRandomUpperCaseLetter();
        }
        return result;
    }
    private updateUILabel(node: Node, coin: any) {
        let label = node.getChildByName("label").getComponent(Label);
        label.string = coin.value;
    }
    private closeIcon(node: Node) {
        node.getChildByName("jin").active = false;
        node.getChildByName("tong").active = false;
        node.getChildByName("zuan").active = false;
    }
}